#include "inc/dev_hp203b.h"
#include "driver/i2c.h"



void HP203B_StartConv(void)
{
	i2c_cmd_handle_t cmd_obj = i2c_cmd_link_create();
	i2c_master_start(cmd_obj);					//起始信号
   	i2c_master_write_byte(cmd_obj, HP20X_I2C_DEV_ID2, 0x1);	//从机地址及读写位
    i2c_master_write_byte(cmd_obj, 0x40, 0x1);	
   	i2c_master_stop(cmd_obj);					//终止信号

    i2c_master_cmd_begin(common_i2c_num, cmd_obj, 100 / portTICK_PERIOD_MS);
    i2c_cmd_link_delete(cmd_obj);
}

u8 HP203B_ReadReg(u8 reg_addr)
{
    u8 data;
	i2c_cmd_handle_t cmd_obj = i2c_cmd_link_create();
	i2c_master_start(cmd_obj);					//起始信号
   	i2c_master_write_byte(cmd_obj, HP20X_I2C_DEV_ID2, 0x1);	//从机地址及读写位
    i2c_master_write_byte(cmd_obj, HP20X_RD_REG_MODE|reg_addr, 0x1);	
    i2c_master_stop(cmd_obj);

    i2c_master_start(cmd_obj);	
    i2c_master_write_byte(cmd_obj, HP20X_I2C_DEV_ID2|0x01, 0x1);
    i2c_master_read_byte(cmd_obj, &data, I2C_MASTER_NACK);
    i2c_master_stop(cmd_obj);

    i2c_master_cmd_begin(common_i2c_num, cmd_obj, 100 / portTICK_PERIOD_MS);
    i2c_cmd_link_delete(cmd_obj);
    return data;
}
    
void HP203B_WriteReg(u8 reg_addr, u8 reg_val)
{
    i2c_cmd_handle_t cmd_obj = i2c_cmd_link_create();
    i2c_master_start(cmd_obj);					//起始信号
    i2c_master_write_byte(cmd_obj, HP20X_I2C_DEV_ID2, 0x1);	//从机地址及读写位
    i2c_master_write_byte(cmd_obj, HP20X_WR_REG_MODE|reg_addr, 0x1);
    i2c_master_write_byte(cmd_obj, reg_val, 0x1);		
    i2c_master_stop(cmd_obj);					//终止信号

    i2c_master_cmd_begin(common_i2c_num, cmd_obj, 100 / portTICK_PERIOD_MS);
    i2c_cmd_link_delete(cmd_obj);
}


float HP203B_ReadData(u8 reg_addr)
{       
    uint8_t buf[3] = {0};
    int data;
    i2c_cmd_handle_t cmd_obj = i2c_cmd_link_create();
    i2c_master_start(cmd_obj);					//起始信号
    i2c_master_write_byte(cmd_obj, HP20X_I2C_DEV_ID2 | I2C_MASTER_WRITE, 0x1);	//从机地址及读写位
    i2c_master_write_byte(cmd_obj, reg_addr, 0x1);		
    //i2c_master_stop(cmd_obj);

    //esp_rom_delay_us(500);

    i2c_master_start(cmd_obj);	
    i2c_master_write_byte(cmd_obj, HP20X_I2C_DEV_ID2 | I2C_MASTER_READ, 0x1);	
    i2c_master_read_byte(cmd_obj, &buf[0], I2C_MASTER_ACK);
    i2c_master_read_byte(cmd_obj, &buf[1], I2C_MASTER_ACK);
    i2c_master_read_byte(cmd_obj, &buf[2], I2C_MASTER_NACK);
    i2c_master_stop(cmd_obj);

    i2c_master_cmd_begin(common_i2c_num, cmd_obj, 1000 / portTICK_PERIOD_MS);
    i2c_cmd_link_delete(cmd_obj);
    data = ((buf[0] << 16) | (buf[1] << 8) | buf[2]) & 0xfffff;
    if(data & 0x80000)data |= 0xfff00000;			//补码处理			
    return data/100.0; //单位 mbar
}

void HP203B_Reset(void)
{
	i2c_cmd_handle_t cmd_obj = i2c_cmd_link_create();
	i2c_master_start(cmd_obj);					//起始信号
	i2c_master_write_byte(cmd_obj, HP20X_I2C_DEV_ID2, 0x1);	//从机地址及读写位
	i2c_master_write_byte(cmd_obj, HP20X_SOFT_RST, 0x1);
	i2c_master_stop(cmd_obj);					//终止信号

	i2c_master_cmd_begin(common_i2c_num, cmd_obj, 100 / portTICK_PERIOD_MS);
	i2c_cmd_link_delete(cmd_obj);
	HP203B_StartConv();
}